package edu.xjdx.os.service.Impl;

import edu.xjdx.os.domain.Administrator;
import edu.xjdx.os.domain.AdministratorExample;
import edu.xjdx.os.domain.Dictionary;
import edu.xjdx.os.domain.DictionaryExample;
import edu.xjdx.os.mapper.AdministratorMapper;
import edu.xjdx.os.mapper.DictionaryMapper;
import edu.xjdx.os.service.AdministratorService;
import edu.xjdx.os.utils.IDGenerator;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdministratorServiceImpl implements AdministratorService {

    @Autowired
    private AdministratorMapper administratorMapper;

    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Override
    public Administrator findByName(String name) {
        AdministratorExample example = new AdministratorExample();
        example.createCriteria().andAdministratorNameEqualTo(name);
        return administratorMapper.selectByExample(example).get(0);
    }
    @Override
    public void add(Administrator administrator){
        administratorMapper.insertSelective(administrator);
    }

    @Override
    public Boolean register(String administratorName,String administratorPassword) {
        DictionaryExample dexample=new DictionaryExample();
        dexample.createCriteria().andDictionaryValueEqualTo("超级管理员");
        Dictionary dictionary= dictionaryMapper.selectByExample(dexample).get(0);
        AdministratorExample example=new AdministratorExample();
        example.createCriteria().andAdministratorNameEqualTo(administratorName);
        List<Administrator>administrators=administratorMapper.selectByExample(example);
        Administrator administrator=null;
        if (administrators.size() > 0) {
            administrator=administrators.get(0);
        }else {
            administrator=new Administrator();
        }
        if(administratorName!=null && administratorPassword!=null){

            administrator.setAdministratorId(IDGenerator.getId());
            administrator.setAdministratorName(administratorName);
            administrator.setAdministratorPassword(administratorPassword);
            administrator.setAdministratorRight(dictionary.getDictionaryId());
            administratorMapper.insertSelective(administrator);
            return true;
        }
        return false;
    }
}
